﻿using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using System.Net;
using System.Text.RegularExpressions;


namespace ProjetoFase2
{
    public partial class FormManageActivities : Form
    {
        public FormManageActivities(string serverIp, int port)
        {
            InitializeComponent();

            if (serverIp != "")
            {
                // initialize the server textboxes
                txtServerIp.Text = serverIp;
                txtServerPort.Text = port.ToString();

                btnLoad_Click(null, null);

                updateDataSets(Residence.listaInativa, "inactive");
            }
            else
            {
                updateDataSets(Residence.listaAtiva, "active");
                updateDataSets(Residence.listaInativa, "inactive");
            }

            if (UserLogin.AccessLevel > 0)
            {
                labelSupervisor.Text = "Current IP is:";
                panelSupervisor.Visible = true;
                txtSupervisorIp.Text = SearchGoodIP(Dns.GetHostEntry(Dns.GetHostName()).AddressList);
                txtSupervisorIp.Enabled = false;
                txtSupervisorPort.Text = "";
                txtSupervisorPort.Enabled = true;
                btnSync.Text = "Listen";
            }
            cmbActive.DataSource = Residence.listaAtiva.Tables["residence"];
            cmbActive.DisplayMember = "address";
            cmbActive.ValueMember = "resi_id";

            txtDistrictResidence.DataBindings.Add(new Binding("Text", cmbActive.DataSource, "district"));

            cmbInactive.DataSource = Residence.listaInativa.Tables["residence"];
            cmbInactive.DisplayMember = "address";
            cmbInactive.ValueMember = "resi_id";
        }

        private static string SearchGoodIP(IPAddress[] ips)
        {
            //Magic...
            string regexpPattern =
                @"^" +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])" +
                @"$";

            foreach (IPAddress ip in ips)
            {
                Match m = Regex.Match(ip.ToString(), regexpPattern);
                if (m.Success == true)
                {
                    return ip.ToString();
                }
            }

            return "IP problem";

        }

        private void loadVisitingResidences(string serverIp, int port)
        {
            ServerInteraction server = new ServerInteraction(serverIp, port);
            
            server.loadActivities(UserLogin.Username, UserLogin.Password);

            // instantiate datasets
            updateDataSets(Residence.listaAtiva, "active");
        }

        private void updateDataSets(DataSet ds, string table_name)
        {
            // update residence datasets
            DatabaseConnector dbCon = new DatabaseConnector(UserLogin.Username, UserLogin.Password);
            ds.Clear();
            dbCon.getResidenceDataSet(table_name, ds);
        }

        private void saveVisitingResidences(string serverIp, int port)
        {
            ServerInteraction server = new ServerInteraction(serverIp, port);
            server.saveActivities(UserLogin.Username, UserLogin.Password);

            // alter residence datasets
            updateDataSets(Residence.listaInativa, "inactive");
        }

        private void FormManageActivities_Load(object sender, EventArgs e)
        {
            switch (UserLogin.AccessLevel)
            {
                case 0:
                    txtNivel.Text = "Trainee";
                    break;
                case 1:
                    txtNivel.Text = "Técnico";
                    break;
                case 2:
                    txtNivel.Text = "Fiscal";
                    break;
            }

            txtDistrict.Text = UserLogin.District;
        }

        private void FormManageActivities_Close(object sender, EventArgs e)
        {
            UserLogin.Logout();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            btnLoad.Enabled = false;
            loadVisitingResidences(txtServerIp.Text, int.Parse(txtServerPort.Text));
            btnLoad.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnSave.Enabled = false;
            saveVisitingResidences(txtServerIp.Text, int.Parse(txtServerPort.Text));
            btnSave.Enabled = true;
        }

        private void btnCriarCE_Click(object sender, EventArgs e)
        {
            btnCriarCE.Enabled = false;
            try
            {
                if (cmbActive.Items.Count == 0)
                    return;

                // get the residence to edit
                DatabaseConnector dbCon = new DatabaseConnector(UserLogin.Username, UserLogin.Password);
                Residence auxResi = dbCon.selectResidence("active", (int)cmbActive.SelectedValue);

                FormEditCertificate form = new FormEditCertificate(auxResi);
                DialogResult foo = form.ShowDialog();
                if (foo == DialogResult.No)
                {
                    // do nothing
                }
                else if (foo == DialogResult.OK)
                {
                    // update the edited certificate and add to inactive list
                    dbCon.deleteResidence("active", auxResi.Resi_id);
                    dbCon.insertResidence("inactive", auxResi);
                    updateDataSets(Residence.listaAtiva, "active");
                    updateDataSets(Residence.listaInativa, "inactive");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            btnCriarCE.Enabled = true;
        }

        private void txtRemove_Click(object sender, EventArgs e)
        {
            if (cmbInactive.Items.Count == 0)
                return;

            // remove from inactive and add to active
            DatabaseConnector dbCon = new DatabaseConnector(UserLogin.Username, UserLogin.Password);
            Residence auxResi = dbCon.selectResidence("inactive", (int)cmbInactive.SelectedValue);
            dbCon.deleteResidence("inactive", auxResi.Resi_id);
            dbCon.insertResidence("active", auxResi);
            updateDataSets(Residence.listaAtiva, "active");
            updateDataSets(Residence.listaInativa, "inactive");
        }

        private void menuLogout_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            if (UserLogin.AccessLevel > 0)
            {
                //listen for entyes
                startListening();
            }
            else
            {
                //send the data
                startSynchronize();
            }

        }

        private void startListening()
        {
            ListenForm liste = new ListenForm(txtSupervisorIp.Text,int.Parse(txtSupervisorPort.Text));
            liste.Show();
        }

        private void startSynchronize()
        {
            SyncForm sync = new SyncForm(txtSupervisorIp.Text, int.Parse(txtSupervisorPort.Text));
            sync.Show();
        }

    }
}